<template>
	<div id="materialEdit">
		<view class="nav-box">
			<view class="nav-box-text">
				<image src="@/static/img/home/person.png" class="person"></image>
				<view class="welcome">
					<view><text>姓名：{{userInfo.nickName}}</text></view>
					<view><text>单位：{{userInfo.dept.deptName}}</text></view>
				</view>
			</view>
		</view>
		<view class="project">
			<text>{{projectInfo.name}}</text>
		</view>
		<view class="uni-list">
			<uni-forms ref="form" :rules="rules" :modelValue="form">
<!-- 				<uni-forms-item label="批次" name="batch">
					<uni-easyinput v-model="form.batch" :inputBorder="false" placeholder="请输入" :disabled="Type =='2'" />
				</uni-forms-item> -->
				<uni-forms-item label="标段" name="bidSection" required>
					<uni-easyinput v-model="form.bidSection" :inputBorder="false" :maxlength="20" placeholder="请输入"
						v-if="Type !='2'"/>
				<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.bidSection}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="材料名称" name="name" required>
					<uni-easyinput v-model="form.name" :inputBorder="false" :maxlength="20" placeholder="请输入" v-if="Type !='2'" />
					<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.name}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="材料代码" name="code">
					<uni-easyinput v-model="form.code" :inputBorder="false" :maxlength="100" placeholder="请输入" v-if="Type !='2'" />
					<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.code}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="规格型号" name="model">
					<uni-easyinput v-model="form.model" :inputBorder="false" :maxlength="100" placeholder="请输入" v-if="Type !='2'" />
					<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.model}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="进场数量" name="number" required> 
					<uni-easyinput v-model="form.number" :inputBorder="false"  placeholder="请输入" type="number" :maxlength="10"
						v-if="Type !='2'"/>
						<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.number}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="出厂批号" name="factoryCode" required>
					<uni-easyinput v-model="form.factoryCode" :inputBorder="false" :maxlength="100" placeholder="请输入"
						v-if="Type !='2'"/>
						<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.factoryCode}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="品牌" name="brand">
					<uni-easyinput v-model="form.brand" :inputBorder="false" :maxlength="100" placeholder="请输入" v-if="Type !='2'" />
					<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.brand}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="供应商" name="supplier">
					<uni-easyinput v-model="form.supplier" :inputBorder="false" :maxlength="100" placeholder="请输入" v-if="Type !='2'" />
					<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.supplier}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="重量" name="supplier">
					<uni-easyinput v-model="form.weight" :inputBorder="false" :maxlength="100" placeholder="请输入" v-if="Type !='2'" />
					<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.weight}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="生产厂家" name="factory" required>
					<uni-easyinput v-model="form.factory" :inputBorder="false" :maxlength="100" placeholder="请输入"
						v-if="Type !='2'"/>
						<view  style="display: flex;height: 100%;"><text v-if="Type =='2'" style="align-self:center">{{form.factory}}</text></view>
				</uni-forms-item>
				<uni-forms-item label="进场日期" name="approach" required>
					<uni-datetime-picker v-model="form.approach" :border="false" type="date" :disabled="Type =='2'" />
				</uni-forms-item>
<!-- 				<uni-forms-item label="验收人" name="users">
					<picker :value="usersIndex" :range="staff">
						<!-- <view class="uni-input">{{staff[usersIndex].name}}</view> -->
<!-- 						<view class="uni-input">{{staff[usersIndex]}}</view>
					</picker>
				</uni-forms-item> --> 
				<uni-list-item  name="users" required>
					<template v-slot:header><text class="slot-box"><text class="is-required">*</text>验收人</text></template>
					<template v-slot:body><text style="width: 0;"></text></template>
					<template v-slot:footer>
						<view class="tree-select" @click="Type=='2'?'':$refs.leadertree._show()">
							{{ form.users.length>0?form.users.map(item=>{return item.userName}).join():'请选择' }}
						</view>
					</template>
				</uni-list-item>
				<uni-forms-item name="files" label="图片"  :id=" Type=='2'?'hinde':''" required>
					<uni-group>
						<uni-file-picker file-mediatype="image" :readonly="Type =='2'" v-model="form.files" limit="9"
							@delete="(e)=>{return delets(e)}" @select="e=>{return detailUpload(e)}"></uni-file-picker>
					</uni-group>
				</uni-forms-item>
				<uni-forms-item name="videoFiles" label="视频"  :id=" Type=='2'?'hinde':''">
					<uni-group v-if="Type !=='2'">
						<uni-file-picker file-mediatype="video" :readonly="Type =='2'" v-model="form.videoFiles" limit="9"
							@delete="(e)=>{return deletsVideo(e)}" @select="e=>{return detailUploadVideo(e)}"></uni-file-picker>
					</uni-group>
					<template v-else>
						<view v-for="video in form.videoFiles" :key="video.id" style="margin: 10px 18px;">
							<video :src="video.url" style="width: 64px;height: 64px;" @play="handlePlay"></video>
						</view>
					</template>
				</uni-forms-item>
			</uni-forms>
			<view v-if="Type =='2'">
				<view class="title">验收记录</view>
				<uni-table class="tables" stripe emptyText="暂无更多数据">
					<uni-tr>
						<uni-th>序号</uni-th>
						<uni-th>验收人</uni-th>
						<uni-th >验收时间</uni-th>
						<uni-th class="Img">出场图片</uni-th>
						<uni-th class="Img">验收图片</uni-th>
						<uni-th>备注</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,i) in table" :key="item.id">
						<uni-td>{{i+1}}</uni-td>
						<uni-td>{{item.createByName}}</uni-td>
						<uni-td>{{item.createTime}}</uni-td>
						<uni-td class="Img">
							<template>
								<view v-for="(res,index) in item.clzmfiles" :key="index">
									<image  class="img1" @tap="preView(res.url)" :src="res.url"></image>
								</view>
							</template>
						</uni-td>
						<uni-td class="Img">
							<template>
								<view v-for="(res,index) in item.ysqkfiles" :key="index">
									<image  class="img1" @tap="preView(res.url)" :src="res.url"></image>
								</view>
							</template>
						</uni-td>
						<uni-td>{{item.msg}}</uni-td>
					</uni-tr>
				</uni-table>
			</view>
		</view>
		<view style="height: 60px;"></view>
		<view class="bottom-nav" v-if="Type !== '2'">
			<button type="primary" :loading="loading" v-if="Type !='2'" size="mini" class="btn"  :disabled="!Btn"
				@click="save(0)">保存</button>
			<button type="primary" :loading="loading" v-if="Type !='2'" size="mini" class="btn"  :disabled="!Btn"
				@click="save(1)">提交</button>
			// <!-- <button type="primary" :loading="loading"  class="btn" @click="audit()">新增</button> -->
			<button type="primary" :loading="loading" v-if="Type =='2'"  @click="Return()" style="width: 100%;">返回</button>
		</view>
		<tki-tree ref="leadertree" :range="staff1"  confirmColor="#4e8af7" :multiple="true" @confirm="personTreeSelect" @cancel="personTreeCancel" :selectParent="false" />
<!-- 		<fui-backdrop :show="showFul" closable @click="showFul=false">
			<image :src="preUrl" mode=""></image>
		</fui-backdrop> -->
	</div>
</template>

<script>
	// import { addMaterial } from '@/api/material/index.js'
	import {
		addMaterial,
		inquirestaff,
		viewDetails,
		updateMaterial
	} from '@/api/material/index.js'
	import {
		imgUpload,
		fileUpload,
		getPerson,
		addCheck,
		updateCheck,
		findDetail,
		handleCheck,
		findHistory
	} from '../../api/inspection/index.js'
	import {decrypt} from '@/common/jsencrpty.js'
	
	export default {
		data() {
			return {
				Btn:true,
				table:[],
				usersIndex: '',
				showFul:false,
				Type: '', //判断编辑详情
				staff: [],
				staff1: [],
				usersIndex: 0,
				files: [],
				userInfo: [],
				projectInfo: [],
				roleStatus: '',
				loading: false,
				form: {
					materialsId: '',
					state: 0,
					batch: '',
					brand: '',
					supplier:'',
					name: '',
					bidSection: '',
					code: '',
					model: '',
					number: '',
					factoryCode: '',
					factory: '',
					approach: '',
					users: [],
					weight:'',
					files: [],
					videoFiles: [],
				},
				// 验证
				rules: {
					name: {
						rules: [{ required: true, errorMessage: '请输入材料名称' }]
					},
					bidSection: {
						rules: [{ required: true, errorMessage: '请输入标段' }]
					},
					number: {
						rules: [
							{ required: true, errorMessage: '请输入入场数量' },
							{ pattern: '^[1-9]\d*|0$', errorMessage: '请输入有效数字' }
						]
					},
					approach: {
						rules: [{ required: true, errorMessage: '请选择进场日期' }]
					},
					factoryCode: {
						rules: [{ required: true, errorMessage: '请输入出厂批号' }]
					},
					factory: {
						rules: [{ required: true, errorMessage: '请输入生产厂家' }]
					},
					users: {
						rules: [{ required: true, errorMessage: '请选择接收人' }]
					},
					files: {
						rules: [{ required: true, errorMessage: '请选择图片' }]
					}
				}
			}
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			this.userInfo = uni.getStorageSync('userInfo')
			this.userInfo.nickName = decrypt(this.userInfo.nickName)
			this.projectInfo = uni.getStorageSync('projectInfo')
			this.materialsId = option.id
			this.Type = option.type
			if (option.type != "1") {
				this.handlecx()
			}
		},
		methods: {
			// 播放试件音视频
			handlePlay(e) {
				let videoContext = uni.createVideoContext('video', this);
				videoContext.requestFullScreen({ direction: 200 });
			},
			//根据id查询姓名
			findUseranme(id){
					  let userName=''
					  this.staff1.forEach(item=>{
						  if(item.children!=null && item.children.length>0){
							  item.children.forEach(res=>{
								  if(id==res.id){
									  userName=res.label
								  }
							  })
						  }
					  })
					  return userName;
			},
			//查找责任人是否选中
			findChecked(id){
					  let isChecked=false
					  this.form.users.forEach(res=>{
						  if(res.userId==id){
							  isChecked=true
						  }
					  })
					  return isChecked
			},
			//查找单位下人员
			findChildren(data){
					return data.map(res=>{
						res.checked= this.findChecked(res.id)
						return res
					 })
			},
			//图片预览
			preView(url){
				let _this = this;
				let imgsArray = [];
				imgsArray[0] = url
				uni.previewImage({
				current: 0,
				urls: imgsArray,
				});
			},
		personTreeSelect(e) {
			this.form.users = []
			if (e && e.length > 0) {
				e.forEach(item=>{
					this.form.users.push({
						userId: item.id,
						userName: item.label
					})
				})
			}
		},
		// 新增
		audit(){

		},
		// 责任人取消选择
		personTreeCancel(e) {
			this.form.liables = []
		},
			delets(e) {
				let index = this.form.files.indexOf(e.tempFile)
				this.form.files.splice(index, 1)

			},
			deletsVideo(e) {
				let index = this.form.videoFiles.indexOf(e.tempFile)
				this.form.videoFiles.splice(index, 1)
			},
			async handlecx() {
				const row1 = await viewDetails(this.materialsId)
				console.log(row1)
				this.form = row1.data
				this.form.files = row1.data.files
				this.form.videoFiles = row1.data.videoFiles.map(i=>({...i,name: i.realName}))
				this.table = row1.data.logs
				if(row1.data.users!=null){
					this.form.users=row1.data.users.map(res=>{
						return {
							userId:res,
							userName:this.findUseranme(res)
						}
					})
				}
				this.staff1=this.staff1.map(item=>{
					item.children=this.findChildren(item.children)
					return item
				})
			},
			// 文件上传成功触发
			fileUpload(e) {
			},
			async save(e) {
				this.$refs['form'].validate().then(res=>{
					this.handleyz(e)
				})
			}, 
			async handleyz(e){
				if (this.Type == '1') {
					const row = await addMaterial({
						// "batch": this.form.batch,
						"approach": this.form.approach,
						"brand": this.form.brand,
						"supplier": this.form.supplier,
						"code": this.form.code,
						"factory": this.form.factory,
						"model": this.form.model,
						"name": this.form.name,
						"number": this.form.number,
						"users": this.handleUser(this.form.users),
						"bidSection": this.form.bidSection,
						"factoryCode": this.form.factoryCode,
						"files": this.form.files,
						"videoFiles": this.form.videoFiles,
						"status": e
						// id:this.projectMe.id  
					})
					if (row.code = 200) {
						let pages = getCurrentPages();
						let prevPage = pages[pages.length - 2];
						prevPage.$vm.handleInitialize();
						uni.navigateBack();
					}
				}
				if (this.Type == '3') {
					const row = await updateMaterial({
						// "batch": this.form.batch,
						"approach": this.form.approach,
						"brand": this.form.brand,
						"supplier": this.form.supplier,
						"code": this.form.code,
						"factory": this.form.factory,
						"model": this.form.model,
						"name": this.form.name,
						"number": this.form.number,
						"users": this.handleUser(this.form.users),
						"bidSection": this.form.bidSection,
						"factoryCode": this.form.factoryCode,
						"files": this.form.files,
						"videoFiles": this.form.videoFiles,
						"status": e,
						id: this.materialsId
					})
					if (row.code = 200) {
						let pages = getCurrentPages();
						let prevPage = pages[pages.length - 2];
						prevPage.$vm.handleInitialize();
						uni.navigateBack();
					}
				}
				
			},
			//处理责任人数据
			handleUser(data){
				return data.map(res=>{
					return res.userId
				})
			},
			Return() {
				uni.navigateBack()
				// uni.navigateTo({
				// 	url: '/pages/material/index'
				// })
			},
			async handlecsh() {
				var that = this
				this.projectMe = uni.getStorageSync('projectInfo')
				const row = await inquirestaff(this.projectInfo.id)
				this.staff = [],
					row.rows.forEach(function(e) {
						that.staff.push(e.nickName)
					})
				this.staff1=row.rows.map(item=>{	
					return {
						id:item.id,
						label:item.deptName,
						children:item.person.map(items=>{
							return {
								id:items.personId,
								label:items.nickName
							}
						})
					}
				})
				if(this.Type != '1'){
				
				this.handlecx()
				}
			},
			detailUpload(e) {
				var that = this
				that.Btn=false
				e.tempFilePaths.forEach(res => {
					imgUpload(res).then(item => {
						let datas = JSON.parse(item)
						if (datas.code == 200) {
							uni.showToast({
								title: '图片上传成功',
							})
							this.form.files.push({
								id: datas.data.id,
								url: datas.data.url
							})
							that.Btn=true
						} else {
							uni.showToast({
								title: datas.msg,
							})
						}
					})
				})
			},
			detailUploadVideo(e) {
				var that = this
				that.Btn=false
				e.tempFilePaths.forEach(res => {
					imgUpload(res).then(item => {
						let datas = JSON.parse(item)
						if (datas.code == 200) {
							uni.showToast({
								title: '图片上传成功',
							})
							this.form.videoFiles.push({
								id: datas.data.id,
								url: datas.data.url,
								name: datas.data.realName
							})
							that.Btn=true
						} else {
							uni.showToast({
								title: datas.msg,
							})
						}
					})
				})
			},
		},
		mounted() {
			this.handlecsh()
		}
	}
</script>
<style lang="scss" scoped>
	.tables{
		.Img{
			width: 12%;
		}
		margin-top: 9.12rpx;
		padding: 0rpx 18.24rpx;
		image{
			width: 80rpx;
			height: 80rpx;
		}
	}
	.is-required {
		color: #f00;
		font-weight: bold;
	}
	.slot-box {
		color: #333;
		width: 70px;
		font-size: 14px;
	}
	.tree-select {
		flex: 1;
		color: grey;
		font-size: 14px;
	}
	#materialEdit {
		min-height: 100vh;
		background-color: #fafafa;

		.nav-box {
			width: 100vw;
			height: 160px;
			margin-top: -44px;
			padding: 56px 20px 56px 20px;
			background-image: url(../../static/img/home/head-bg.png);

			.nav-box-text {
				height: 50px;
				display: flex;
				align-items: center;

				.person {
					width: 48px;
					height: 48px;
				}

				.welcome {
					color: #333;
					font-size: 32rpx;
					margin-left: 40rpx;
				}
			}
		}

		.project {
			padding: 10px;
			border-radius: 8px;
			background-color: #fff;
			margin: -32px 20px 0 20px;
			box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, .1);

			text {
				font-size: 14px;
				font-weight: 700;
			}
		}

		.uni-list {
			background-color: #fff;
			margin: 10px 20px 0 20px;
			box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, .1);

			/deep/ .uni-forms-item__inner {
				padding: 0 10px;
				border-bottom: 1rpx solid #bfbfbf;
			}

			/deep/ .uni-error-message {
				right: 0;
				left: auto;
				margin-right: 5px;
			}

			/deep/ .uni-date__x-input {
				height: 36px;
				line-height: 36px;
			}

			/deep/ .uni-group {
				margin-top: 0 !important;
			}

			.uni-forms-item {

				&:last-child {
					/deep/ .uni-forms-item__inner {
						border-bottom: 0;
					}
				}
			}
		}

		.bottom-nav {
			display: flex;
			align-items: center;
			left: 0;
			bottom: 0;
			width: 100vw;
			height: 50px;
			padding: 10px;
			position: fixed;
			background-color: #fff;
			box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, .1);
		}

		.runxx {
			display: flex;
			align-items: center;
		}
	}
	.img1{
		height: 40rpx;
		width: 40rpx;
		img{
		height: 100%;
		width: 100%;
		}
	}
	#hinde{
		::v-deep .is-add{
			display: none!important;
		}
	}
</style>
